<?php

namespace app\admin\controller\facrm\setting;

use app\admin\model\facrm\CloudcallLog;
use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\Queue;
use think\Validate;

/**
 * 云呼管理
 * @icon fa fa-tags
 */
class Cloudcall extends Backend
{

    protected $key = "cloudcall";
    protected $addon_config = array();
    protected $noNeedRight = ['selectpage'];
    protected $data_temp = array();

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\facrm\Setting();
    }

    /**
     * 呼叫
     * @param string $type  customer
     * @param $typeid 对于模型的ID
     * @param string $field 号码字段
     * @param string $prefix 拨打前加参数
     * @return string
     * @throws Exception
     */
    public function call($typeid,$type="customer",$field='mobile',$prefix=''){
        $name=$this->request->request('name');
        if (!$typeid||!$type||!$field) $this->error(__("参数有误"));
        try {
            //获取号码
            switch ($type) {
                case 'customer':
                    $this->model = new \app\admin\model\facrm\Customer();
                    break;
                case 'customer_contacts':
                    $this->model = new \app\admin\model\facrm\customer\Contacts();
                    break;
                default:

                    $this->model = model('\app\admin\model\facrm\\' . ucfirst($type));
                    break;
            }
            $mobile=$this->model->where('id',$typeid)->value($field);
            if (!$mobile) $this->error(__("联系方式不存在"));
            //获取云呼配置
            $all_types =  \addons\facrm\library\cloudcall\Call::getProviders();
            $keys = "";
            foreach ($all_types as $v) {
                $keys .= $keys ? ',' . $this->key. $v : $this->key . $v;
            }
            $settingModel = new \app\admin\model\facrm\Setting();
            $setting= $settingModel->where('key', 'in', $keys)->where('status', 1)->find();//只找一条云呼通道

            if (!$setting) {
                $this->error(__("云呼通道没有配置，请先配置"));
            }
            //获取坐席
            $cloudcallModel = new \app\admin\model\facrm\Cloudcall();
            $callrow=$cloudcallModel->where('admin_id',$this->auth->id)->where('cloud',$setting->describe)->where('status',1)->find();

            if (!$callrow) $this->error(__("您当前账号没有配置坐席"));
            $setting=$setting->toArray();
            $setting['key']=$setting['describe'];
            $setting=array_merge($setting,$setting['values']);
            $call= \addons\facrm\library\cloudcall\Call::instance($setting);

            $exten_type=\think\Cookie::get("facrm_extentype");//云呼通话方式
            $data['exten']=$mobile;
            $data['from_exten']=$callrow['from_exten'];
            $data['exten_type']=$exten_type?$exten_type:$callrow['exten_type'];

            $result=$call->call($data,$callrow);
            if (!$result){
                $this->error($call->getError());
            }
            //成功拨打钩子
            hook('cloudcall_success', ['typeid' => $typeid, 'type' => $type, 'name' => $name, 'data' => $data, 'callrow' => $callrow]);

            //保存通话记录
            $cloudcallLog = new \app\admin\model\facrm\CloudcallLog();

            $cloudcallLog->isUpdate(false)->save([
                'admin_id' => $this->auth->id,
                'cloud' => $callrow['cloud'],
                'from_exten' => $callrow['from_exten'],
                'exten_type' => $data['exten_type'],
                'name' => $name,
                'source' => $type,
                'source_id' => $typeid,
                'status' => 0,
                'call_no' => '',
                'called_no' => $mobile,
                'action_id' => $result['ActionID'],
            ]);



            $this->success(__("呼叫成功"));

        }catch (Exception $e){
            $this->error($e->getMessage());
        }
        $this->error();
    }


    /**
     * 查看列表
     * @return string|\think\response\Json
     * @throws \think\Exception
     */
    public function index()
    {

        if ($this->request->isAjax()) {
            $result = array("total" => count($this->data_temp), "rows" => $this->data_temp);

            return json($result);
        }
        $this->view->assign('data_temp', []);
        $this->view->assign('call_types', \addons\facrm\library\cloudcall\Call::getProviders());
        return $this->view->fetch();
    }
    /**
     * 修改
     * @return mixed
     */
    public function edit($key = null)
    {
        if (!$key)
            $this->error(__("选择有误"));
        $newkey =$this->key.$key ;
        $row = $this->model->where('key', $newkey)->find();



        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params['key'] = $newkey;
                $params['describe'] = $key;
                $result = false;
                Db::startTrans();
                try {

                    if (!$row) {
                        //添加
                        $result = $this->model->allowField(true)->save($params);
                    } else {
                        //修改
                        $result = $row->allowField(true)->save($params);
                    }

                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign("row", $row);
        return $this->view->fetch(strtolower($key));
    }

    /**
     * 坐席列表
     * @param null $key
     */
    public function fromexten($key = null){
        if (!$key)
            $this->error(__("选择有误"));

        if ($this->request->isAjax()) {
            $this->model=new \app\admin\model\facrm\Cloudcall();
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->with(['admin'=>function($q){
                    $q->field('id,nickname');
                }])
                ->where('cloud',$key)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $total = $this->model
                ->where($where)
                ->where('cloud',$key)
                ->order($sort, $order)
                ->count();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $this->assignconfig('callkey',$key);
        return $this->view->fetch();
    }

    /**
     * 坐席添加\修改
     */
    public function fromextenedit($key = null,$ids=null){
        if (!$key)
            $this->error(__("选择有误"));
        $this->model=new \app\admin\model\facrm\Cloudcall();
        $row=array();


        if ($this->request->isPost()) {

            $params = $this->request->post("row/a");
            if ($params) {
                $params['cloud'] = $key;
                $result = false;
                Db::startTrans();
                try {
                    $row = $this->model->where('cloud', $key)->where('admin_id',$params['admin_id'])->find();
                    if (!$row) {
                        //添加
                        $result = $this->model->allowField(true)->save($params);
                    } else {
                        //修改
                        $result = $row->allowField(true)->save($params);
                    }

                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if ($ids){
            $row = $this->model->where('cloud', $key)->find($ids);
        }
        $this->view->assign("row", $row);
        $this->assignconfig('callkey',$key);
        return $this->view->fetch();

    }

    /**
     * 坐席删除
     * @param null $ids
     */
    public function fromextendel($ids=null){
        $this->model=new \app\admin\model\facrm\Cloudcall();
        return parent::del();

    }


    /**
     * 呼叫日志查看
     */
    public function log(){


        if ($this->request->isAjax()) {
            $this->model = new \app\admin\model\facrm\CloudcallLog();
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->with(['admin' => function ($q) {
                    $q->field('id,nickname');
                }])

                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }


        return $this->view->fetch();
    }


    /**
     * 添加
     * @Internal
     * @return mixed
     */
    public function add()
    {
        $this->error();
    }


    /**
     * @Internal
     * @return mixed
     */
    public function del($ids = "")
    {
        $this->error();
    }
    /**
     * @Internal
     * @return mixed
     */
    public function multi($ids = "")
    {
        $this->error();
    }

    /**
     * 统计
     */
    public function statistics(){

        if ($this->request->isAjax()) {
            $this->model =new CloudcallLog();
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where('status',1)
                ->group('admin_id')
                ->count();

            $list = $this->model
                ->where($where)
                ->field("*, count(*) as count,sum(call_time_length) as call_time_length")
                ->group('admin_id')
                ->where('status',1)
                ->order('call_time_length','desc')
                ->fetchSql(false)
                ->limit($offset, $limit)
                ->select();


            foreach ($list as &$row){
                $row->admin;
                $row->call_time_length=number_format($row->call_time_length/60,2) ;
            }

            $result = array("total" => $total, "rows" => $list);
            return json($result);

        }

        return $this->view->fetch();

    }

    /**
     * 日志详情
     */
    public function logdetail($ids = "")
    {
        $this->model = new \app\admin\model\facrm\CloudcallLog();
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (!$this->auth->isSuperAdmin()){
            $childrenAdminIds =$this->auth->getChildrenAdminIds(true);
            if (!$row['admin_id'] || !in_array($row['admin_id'], $childrenAdminIds)) {
                $this->error(__('您没有权限查看'));
            }
        }

        $this->view->assign("row", $row->toArray());
        return $this->view->fetch();
    }

}